from io import BytesIO
import j_ocr
import cv2
import numpy as np
import requests
from PIL import Image
from ultralytics import YOLO

import save_tuchuang
import wenxocr
import xueqing
import znyj
import zuowenocr
from 分割 import dati


def shi_juan(uid,url):
    model = YOLO(model='best.pt')
    url = [url]
    images = []
    for i in url:
        response = requests.get(i)
        if response.status_code == 200:
            # 从响应内容中获取图片数据
            img = Image.open(BytesIO(response.content))
            img_array = np.array(img)
            images.append(img_array)
    res = dati.A(images, model)
    o=0
    for i in range(0, len(images)):
        o = o+1
        img = images[i]
        data = res[i]
        img_name = []
        for x in data:
            o = o + 1
            id = x["id"]
            x1, y1, x2, y2 = x["xyxy"]
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(img, str(id), (x1 , y1 + 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            if o==4:
                cv2.putText(img, str(7), (x2-30, y1+35), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
            s = f"{uid}_{id}.jpg"
            cv2.imwrite(s, img[y1:y2, x1:x2])
            img_name.append(s)
        cv2.imwrite(f'{uid}_1000.jpg', img)
        img_name.append(f'{uid}_1000.jpg')
        save_tuchuang.save_j(img_name)
        img_name = [f"http://43.139.56.166:9001/ksxt/{i}" for i in img_name]
        return j_ocr.shi_bie(img_name)
def ocr_zuowen(url):
    if type(url)!=type([]):
         url = [url]
    result =  zuowenocr.shi_bie(url)
    return result
def xueqing_1(uid,data):
    for item in data:
        # 使用字典推导式创建一个新的字典，其中uid是第一个键值对
        # 然后使用{**new_dict, **item}来合并字典，确保uid在最前面
        new_item = {"学号": uid, **item}
        item.clear()  # 清空原字典
        item.update(new_item)  #
    return xueqing.run(data)
def trim_string(input_string):
    # 检查字符串长度是否足够删除前7个字符和最后3个字符
    if len(input_string) >= 10:
        # 删除前7个字符和最后3个字符
        trimmed_string = input_string[7:-3]
        return trimmed_string
    else:
        # 如果字符串长度不足，返回原始字符串或者错误信息
        return "输入字符串长度不足，无法删除指定数量的字符。"
def ocr(url):
    if type(url)!=type([]):
         url = [url]
    result =  wenxocr.shi_bie(url)
    return result
def se_read(discipline,rulse,standard,student1,student2,score):
    print(rulse)
    if(rulse=="1"):
        rulse=score
        resu = sho_or_image(discipline=discipline, rules=rulse, standard=standard, student1=student1, student2=student2)
        huda_str = trim_string(resu)
        print(huda_str)
        return huda_str
    else:
        resu = sho_or_image(discipline=discipline, rules=rulse, standard=standard, student1=student1, student2=student2)
        print(resu)
        huda_str = trim_string(resu)
        print(huda_str)

        return huda_str
def sho_or_image(discipline,rules,standard,student1,student2):
    if(len(student1)>5):
        if(discipline=="英语作文"):
            resu_shi = ocr_zuowen(student1)
        else:
            resu_shi = ocr(student1)
        print("图片答案识别成功")
        return znyj.znyj(discipline,rules,standard,resu_shi)
    else:
        print("文字答案载入成功")
        return znyj.znyj(discipline,rules,standard,student2)
if __name__ == '__main__':

    xueqing_1("666",list([{"name":"第一次测试","yuwen":"120","math":"130","english":"110","wuli":"80","huaxue":"70","shengwu":"60"},{"name":"第二次测试","yuwen":"120","math":"110","english":"102","wuli":"60","huaxue":"70","shengwu":"80"},{"name":"第三次测试","yuwen":"120","math":"130","english":"125","wuli":"75","huaxue":"80","shengwu":"88"}]))
    exit(0)
    shi_juan(15,"http://43.139.56.166:9001/ksxt/7c86777093e927b6da24c961671fb423.jpg")
